package org.gokeep.communication.engine.udp;

import java.net.DatagramPacket;
import java.nio.charset.Charset;

/**
 * @author xuning
 */
public abstract class MessageProcess {

    private DatagramPacket packet;

    /**
     * 处理执行器
     *
     * @param datagramPacket
     */
    public void execute(DatagramPacket datagramPacket) {
        this.packet = datagramPacket;
        process(this.packet);
    }

    /**
     * 获取数据包的长度
     *
     * @param datagramPacket
     * @return
     */
    public int getPacketLength(DatagramPacket datagramPacket) {
        return this.packet.getLength();
    }

    /**
     * 获取string解析
     *
     * @return
     */
    public String string() {
        int length = getPacketLength(this.packet);
        return new String(packet.getData(), 0, length, Charset.defaultCharset());
    }


    /**
     * 获取字节数组
     *
     * @return
     */
    public byte[] bytes() {
        byte[] data = new byte[this.packet.getLength()];
        System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());
        return data;
    }

    /**
     * 获取主机地址
     *
     * @return
     */
    public InetAddress getAddress() {
        return InetAddress.build(this.packet.getAddress().getHostAddress(), this.packet.getPort());
    }

    /**
     * 处理方法
     *
     * @param datagramPacket
     */
    public abstract void process(DatagramPacket datagramPacket);
}
